package shijian.database.utils;


import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");

        Properties prop = new Properties();
        try {
            prop.load(in);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        driver = prop.getProperty("jdbc.driver");
        url = prop.getProperty("jdbc.url");
        username = prop.getProperty("jdbc.username");
        password = prop.getProperty("jdbc.password");

        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(
                url, username, password
        );
    }

    public static void close(ResultSet rs, PreparedStatement stmt, Connection conn)
    {
        if (rs != null)   try { rs.close(); }   catch (SQLException ignored) {}
        if (stmt != null) try { stmt.close(); } catch (SQLException ignored) {}
        if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
    }

    public static void close(PreparedStatement stmt, Connection conn)
    {
        if (stmt != null) try { stmt.close(); } catch (SQLException ignored) {}
        if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
    }

    public static void close(ResultSet resultSet)
    {
        if (resultSet != null) try { resultSet.close(); } catch (SQLException ignored) {}
    }

    public static PreparedStatement createPreparedStatement(Connection conn, String sql)
            throws SQLException
    {
        PreparedStatement stmt = conn.prepareStatement(sql);
        return stmt;
    }


    public static ResultSet executeQuery(String sql) throws RuntimeException, SQLException {

        Connection connection = getConnection();

        PreparedStatement preparedStatement = createPreparedStatement(connection, sql);

        ResultSet resultSet = preparedStatement.executeQuery();

//        close(preparedStatement, connection);

        return resultSet;

    }

    public static Boolean execute(String sql) throws RuntimeException, SQLException {

        Connection connection = getConnection();

        PreparedStatement preparedStatement = createPreparedStatement(connection, sql);

        boolean execute = preparedStatement.execute();

        close(preparedStatement, connection);

        return execute;

    }


}
